//
//  YCUserAccount.swift
//  WeiboDemo
//
//  Created by 尹成 on 2017/1/13.
//  Copyright © 2017年 yc. All rights reserved.
//

import UIKit

class YCUserAccount: NSObject {
    
    /// token
    var access_token:String? //= "2.00JF3MPGxJ2KKDb28346cfd82cNv_B"
    
    /// 用户唯一标识
    var uid:String?// = "5721386855"
    
    /// token过期时间,单位s ，开发者5年，使用者3天
    var expires_in:TimeInterval = 0{
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期，由👆计算出来
    var expiresDate:Date?
    
    override var description: String{
        return yy_modelDescription()
    }
    
    
    /// 昵称
    var screen_name:String?
    
    /// 用户头像 180*180
    var avatar_large:String?
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    override init() {
        
        super.init()
        
        guard let user = UserDefaults.standard.object(forKey: "UserAccount") else {
            return
        }
        
        yy_modelSet(withJSON: user)
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            //token 过期,需重新登录
            yy_modelSet(withJSON: [:])
            UserDefaults.standard.removeObject(forKey: "UserAccount")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: YCUserShouldLoginNotification), object: "Token Error!")
        }
        
    }
    
    func yc_set(with:Any? ,userInfo:Any?) -> () {
        let dict = with as? [String : AnyObject] ?? [:]
        yy_modelSet(withJSON: dict)
        
        if (userInfo != nil) {
            
            let userInfo = userInfo as? [String : AnyObject] ?? [:]
            yy_modelSet(withJSON: userInfo)
            
            var UserDict = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
            /// 保存到本地时需将字典中的expire_in去掉，否则从本地取数据时会重新计算结束时间
            UserDict.removeValue(forKey: "expires_in")
            
            UserDefaults.standard.set(UserDict, forKey: "UserAccount")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: YCUserLoginSuccessNotification), object: nil)
        }
        
    }
}
